let fnApiAjax = function (method, url, data, dataType, suc, err) { // ajax请求方法
  data = data || null
  dataType = dataType || 'json'
  suc = suc || null
  err = err || null
  if (url.indexOf('?') > -1) {
    url = url + '&_async=1'
  }else {
    url = url + '?_async=1'
  }
  $.ajax({
    type: method,
    url: api_host + url,
    data: data,
    dataType: dataType,
    crossDomain: true,
    xhrFields: {
      withCredentials: true
    },
    success: function (response) {
      console.log('code:' + response.code + ' msg:' + response.msg)
      if (typeof response === 'string') {
        response = $.parseJSON(response)
      }
      if (response.code == 0) {
        if (typeof suc === 'function') {
          suc(response.data)
        }
      }
      else if (response.code == 90001) {
        layer.msg(response.msg)
        fnRedirect(response.data.redirect, 500)
      }else {
        layer.msg(response.msg)
        err(response.data)
      }
    },
    error: fnAjaxError,
    complete: fnAjaxComplete
  })
}

let fnReqVerify = function (req, verify) { // 参数验证
  for (field in verify) {
    if (!req.hasOwnProperty(field)) {
      let param = verify[field]
      layer.msg(param.errMsg)
      return false
    } else {
      let val = req[field]
      let param = verify[field]
      if (param.hasOwnProperty('required') && param.required === true) {
        if (val == '') {
          layer.msg(param.errMsg)
          return false
        }
      }
      if (param.hasOwnProperty('pattern')) {
        let pattern = param.pattern
        if (!pattern.test(val)) {
          layer.msg(param.errMsg)
          return false
        }
      }
      if (param.hasOwnProperty('same')) {
        let same = param.same
        if (val != req[same])
        {
          layer.msg(param.errMsg)
          return false
        }
      }
    }
  }
  return true
}

// 加载中效果
let fnLoading = function () {
  layer.load(2)
}
// 取消加载效果
let fnStopLoading = function () {
  layer.closeAll('loading')
}

let fnAjaxComplete = function () {
  layer.closeAll('loading')
  fnBtnAble()
}

let fnAjaxError = function () {
  fnStopLoading()
  layer.msg("服务器内部错误")
}

let fnReload = function () {
  setTimeout(function () {
    window.location.reload()
  }, 500)
}

let fnRedirect = function (url, time) {
  setTimeout(function () {
    window.location.href = url
  }, time)
}

let fnBtnDisable = function ($btn) {
  $btn.attr('disabled', 'disabled')
}

let fnBtnAble = function () {
  $("button.submit").removeAttr('disabled')
}